package fun.ticsmyc.rpc.nacos.loadbalance.impl;

import com.alibaba.nacos.api.naming.pojo.Instance;
import fun.ticsmyc.rpc.nacos.loadbalance.LoadBalancer;

import java.util.List;
import java.util.Random;

/**
 * @author Ticsmyc
 * @date 2020-10-30 11:45
 */
public class RandomNacosLoadBalancer implements LoadBalancer {

    private RandomNacosLoadBalancer(){}
    private static volatile RandomNacosLoadBalancer INSTANCE;
    private static Random random;

    public static RandomNacosLoadBalancer getInstance(){
        if(INSTANCE ==null){
            synchronized (RandomNacosLoadBalancer.class){
                if(INSTANCE == null){
                    INSTANCE = new RandomNacosLoadBalancer();
                    random = new Random();
                }
            }
        }
        return INSTANCE;
    }


    @Override
    public Instance select(List<Instance> instances) {
        return instances.get(random.nextInt(instances.size()));
    }
}
